package com.devbobcorn.nekorization.client.rendering;

import com.devbobcorn.nekorization.client.event.ClientModEventSubscriber;
import com.devbobcorn.nekorization.client.model.NekoModel;
import com.devbobcorn.nekorization.client.model.SpriteModel;
import com.devbobcorn.nekorization.entities.ModEntityType;
import com.devbobcorn.nekorization.entities.NekoEntity;
import com.devbobcorn.nekorization.entities.SpriteEntity;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.blaze3d.vertex.VertexConsumer;
import com.mojang.math.Vector3f;

import net.minecraft.client.model.geom.EntityModelSet;
import net.minecraft.client.model.geom.ModelPart;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.entity.RenderLayerParent;
import net.minecraft.client.renderer.entity.layers.RenderLayer;
import net.minecraft.client.renderer.texture.OverlayTexture;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.world.entity.EntityType;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;

@OnlyIn(Dist.CLIENT)
public class NekoSpriteOnHeadLayer<T extends NekoEntity> extends RenderLayer<T, NekoModel<T>> {
    private final SpriteModel<SpriteEntity> model;

    public NekoSpriteOnHeadLayer(RenderLayerParent<T, NekoModel<T>> renderer, EntityModelSet models) {
        super(renderer);
        this.model = new SpriteModel<>(models.bakeLayer(ClientModEventSubscriber.SPRITE));
    }

    public void render(PoseStack stack, MultiBufferSource buffers, int l, NekoEntity entity, float r, float g, float s, float t, float b, float a) {
        CompoundTag compoundtag = entity.getHeadEntity();
        EntityType.byString(compoundtag.getString("id")).filter((type) -> {
            return type == ModEntityType.$SPRITE_TYPE.get();
        }).ifPresent((type) -> {
            stack.pushPose();
            ModelPart head = getParentModel().getHead();
            stack.translate(0.0D, entity.isCrouching() ? -1.8 : -2.0, -head.xRot);
            stack.translate(head.x, head.y, head.z);
            stack.mulPose(Vector3f.YP.rotation(head.yRot));
            stack.mulPose(Vector3f.XP.rotation(head.xRot));
            VertexConsumer vertexconsumer = buffers.getBuffer(this.model.renderType(SpriteRenderer.GRAY));
            this.model.renderToBuffer(stack, vertexconsumer, l, OverlayTexture.NO_OVERLAY, r, g, b, a);
            stack.popPose();
        });
    }
}